package com.campus.shop.controller.web;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.campus.shop.common.ConstantProperties;
import com.campus.shop.common.Result;
import com.campus.shop.controller.web.vo.UserAddressVo;
import com.campus.shop.entity.UserAddress;
import com.campus.shop.mapper.UserAddressMapper;
import com.campus.shop.service.UserAddressService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

/**
 * 控制器
 *
 * @author xr
 * @since 2024-01-16 15:12:47
 */
@RestController
@RequestMapping("/web/user-address")
public class UserAddressController extends BaseWebController {

    @Resource
    private UserAddressService userAddressService;
    @Resource
    private UserAddressMapper userAddressMapper;
    // 新增或者更新
    @PostMapping
    public Result save(@RequestBody UserAddress userAddress) {
        userAddressService.saveOrUpdate(userAddress);
        return Result.success();
    }

    //获取地址列表(亮点：通过数据流筛选满足条件的id)
    @PostMapping("/get-user-address")
    public Result getUserAddress(){
        QueryWrapper<UserAddress> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",getUserId());
        wrapper.orderByDesc("is_default");
        wrapper.orderByDesc("created_at");
        List<UserAddress> list = userAddressMapper.selectList(wrapper);
        Integer defaultId = list.stream()
                .filter(obj -> obj.getIsDefault() == 1)  // IsDefault=1的对象
                .map(UserAddress::getId)  // 获取IsDefault
                .findFirst()  // 获取第一个IsDefault（如果存在）
                .orElse(list.get(0).getId());// 如果不存在IsDefault=1的对象，则返回列表的第一个id

        int count = list.size();
        int leftCount = ConstantProperties.addressCount - count;
        HashMap<String, Object> res = new HashMap<>();
        res.put("list",list);
        res.put("count",count);
        res.put("leftCount", leftCount);
        res.put("defaultId",defaultId);
        return Result.success(res);
    }

    //添加地址
    @PostMapping("/add-user-address")
    public Result addUserAddress(@RequestBody UserAddressVo userAddress){
        Integer userId = Integer.valueOf(getUserId());
        userAddressService.checkAddress(userAddress, userId);
        UserAddress address = new UserAddress();
        address.setAddress(userAddress.getAddress());
        address.setTelephone(userAddress.getTelephone());
        address.setUserName(userAddress.getUserName());
        address.setIsDefault(userAddress.getIsDefault() == true ? 1 : 0);
        address.setUserId(userId);
        userAddressService.insertUserAddress(address);
        return Result.success();
    }
    //删除地址
    @PostMapping("/del-user-address")
    public Result delUserAddress(@RequestParam("id") Integer id){
        Boolean res = userAddressService.deleteUserAddress(Long.valueOf(id));
        return res ? Result.success() : Result.error();
    }

    //设为默认
    @PostMapping("/set-default")
    public Result setDefault(@RequestParam("id") Integer id){
        userAddressMapper.updateAllByUserId(Integer.valueOf(getUserId()));
        userAddressService.update(Wrappers.<UserAddress>update().lambda().eq(UserAddress::getId, id).set(UserAddress::getIsDefault, 1));
        return Result.success();
    }

}


